package com.handpay.zztong.hp.swiper.widget;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff.Mode;
import android.graphics.Rect;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import com.handpay.zztong.hp.R;
import com.handpay.zztong.hp.SwiperCardKLFActivity;
import com.handpay.zztong.hp.base.activity.ZZTongActivity;
import com.handpay.zztong.hp.log.HPLog;

public class SwiperCardBluetoothView extends SurfaceView {

    // 背景图
    private Bitmap cardImage;
    // private Bitmap titleImage;
    private Bitmap vposImage;
    // private Bitmap phoneImage;
    private Bitmap backImage;
    private int topPosition = 0;
    private int spacePostion = 0;

    private boolean isBack = false;
    SurfaceHolder surfaceHolder;
    float rotate = 0;

    private MyThread thread = null;

    public static int frameCount = 0;
    private float backLeftMin, backLeftMax, backHeightMax;
    private SwiperCardKLFActivity.BackListener backListener;

    public SwiperCardBluetoothView(Context context, AttributeSet set) {
        super(context, set);
        surfaceHolder = this.getHolder();// 获取holder
        surfaceHolder.setFormat(PixelFormat.TRANSPARENT);
        setFocusable(true);
        setZOrderOnTop(true);
        frameCount = 0;
        thread = new MyThread();
        thread.start();
    }

    private void init() {
        cardImage = BitmapFactory.decodeResource(getResources(),
                R.drawable.card);
        // navigation_bar_bg = BitmapFactory.decodeResource(getResources(),
        // R.drawable.navigation_bar_bg);
        // titleImage = BitmapFactory.decodeResource(getResources(),
        // R.drawable.skts);
        vposImage = BitmapFactory.decodeResource(getResources(),
                R.drawable.equipmenton);
        // phoneImage = BitmapFactory.decodeResource(getResources(),
        // R.drawable.shuacardbot);
        backImage = BitmapFactory.decodeResource(getResources(),
                R.drawable.erro);

        backLeftMin = ZZTongActivity.screenWidth - backImage.getWidth() - 20
                * getResources().getDisplayMetrics().density;
        backHeightMax = backImage.getHeight();
        backLeftMax = ZZTongActivity.screenWidth - 20
                * getResources().getDisplayMetrics().density;
        spacePostion = getResources()
                .getDimensionPixelSize(R.dimen.title_dimen);
        // topPosition = (Main.screenHeight - titleImage.getHeight()
        // - phoneImage.getHeight() - cardImage.getHeight()/2 - spacePostion -
        // navigation_bar_bg.getHeight()) / 2;
        topPosition = (ZZTongActivity.screenHeight - cardImage.getHeight() / 2 - spacePostion) / 2;
    }

    public void doDestroy() {
        try {
            thread.isDo = false;
            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    if (cardImage != null && !cardImage.isRecycled()) {
                        cardImage.recycle();
                        cardImage = null;
                    }

                    // if(titleImage!=null && !titleImage.isRecycled()){
                    // titleImage.recycle();
                    // titleImage = null;
                    // }

                    if (vposImage != null && !vposImage.isRecycled()) {
                        vposImage.recycle();
                        vposImage = null;
                    }
                    if (backImage != null && !backImage.isRecycled()) {
                        backImage.recycle();
                        backImage = null;
                    }
                    // if(phoneImage!=null && !phoneImage.isRecycled()){
                    // phoneImage.recycle();
                    // phoneImage = null;
                    // }

                    System.gc();
                }
            }, 1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 自定义线程类
    class MyThread extends Thread {
        public boolean isDo = true;

        public MyThread() {
            super("SwiperCardView");
        }

        @Override
        public void run() {
            init();
            while (isDo) {
                update();
            }
        }
    }

    // Caojun
    private void paint(Canvas canvas) {
        try {
            frameCount++;
            // ----------------首次进入停止几秒再进行动画-----------------------
            if (surfaceHolder == null)
                return;
            if (canvas == null || cardImage == null || cardImage.isRecycled() ||
                    // titleImage ==null || titleImage.isRecycled()||
                    vposImage == null || vposImage.isRecycled())
                // phoneImage ==null || phoneImage.isRecycled())
                return;
            canvas.drawColor(Color.TRANSPARENT, Mode.CLEAR);
            Paint mPaint = new Paint();
            mPaint.setAntiAlias(true);
            mPaint.setDither(true);

            // 创建矩阵以控制图片旋转和平移
            Matrix m = new Matrix();
            // 设置左边距和上边距
            // 绘制问号图
            if (isBack) {
                float displacement = (rotate) / 5;
                if (displacement <= 1) {
                    rotate = rotate - 1;
                } else {
                    rotate = rotate - displacement;
                }
                if (rotate <= 0) {
                    rotate = 0;
                    isBack = false;
                }
            }
            if (!isBack) {
                rotate += 2 * getResources().getDisplayMetrics().density;
            }
            // canvas.drawBitmap(
            // vposImage,
            // (Main.screenWidth - phoneImage.getWidth()) / 2,
            // topPosition + titleImage.getHeight()
            // + spacePostion + cardImage.getHeight()/2 - vposImage.getHeight(),
            // mPaint);
            // m.postTranslate(rotate,
            // topPosition + titleImage.getHeight()
            // + spacePostion + cardImage.getHeight()/3 -
            // vposImage.getHeight());
//			HPLog.i("", "screenWidth:" + ZZTongActivity.screenWidth + "screenHeight:" + ZZTongActivity.screenHeight +" vposWidth" +
//                    vposImage.getWidth()
//                    + "cardImage:" + cardImage.getHeight() +
//                    "topPos:" + topPosition + " spacePos:" + spacePostion);
            int left = (ZZTongActivity.screenWidth - vposImage.getWidth()) / 2;
            int top = ZZTongActivity.screenHeight - vposImage.getHeight() - spacePostion
                    - cardImage.getHeight() / 2;// spacePostion +
            // cardImage.getHeight()/2;

//			HPLog.i("","left:" + left + " top:" + top);
            m.postTranslate(rotate, top - cardImage.getHeight() / 2);
            if (cardImage == null || cardImage.isRecycled()
                    || vposImage == null || vposImage.isRecycled()) {
                return;
            }
            canvas.drawBitmap(cardImage, m, mPaint);
            canvas.drawBitmap(vposImage, left, top, mPaint);
            canvas.drawBitmap(backImage, ZZTongActivity.screenWidth - backImage.getWidth() - 20 * getResources().getDisplayMetrics().density,
                    20 * getResources().getDisplayMetrics().density,
                    mPaint);
            // 计算文本的高度并绘制
            String text = getContext().getText(R.string.please_swiper)
                    .toString();
            float textSize = getContext().getResources().getDimension(
                    R.dimen.twenty_sp);
            mPaint.setTextSize(textSize);
            mPaint.setColor(getContext().getResources().getColor(
                    R.color.keyboardnumber));
            Paint.FontMetrics fm = mPaint.getFontMetrics();
            int textHeight = (int) Math.ceil(fm.descent - fm.top);
            //绘制“请刷卡”
            Rect bounds = new Rect();
            mPaint.getTextBounds(text, 0, text.length(), bounds);
            canvas.drawText(
                    text,
                    (ZZTongActivity.screenWidth - bounds.width()) / 2,
                    (float) (top - cardImage.getHeight() / 2 - spacePostion - textHeight),
                    mPaint);
            //绘制“若使用IC卡读取，在交易完成前请勿将卡拔出卡槽”
            String icText = getContext().getText(R.string.please_ic_swiper_1).toString();
            bounds = new Rect();
            mPaint.getTextBounds(icText, 0, icText.length(), bounds);
            float topText = (float) (top + vposImage.getHeight() + spacePostion);
            canvas.drawText(
                    icText,
                    (ZZTongActivity.screenWidth - bounds.width()) / 2,
                    topText,
                    mPaint);
            topText = topText + spacePostion + (bounds.bottom + bounds.height());
            icText = getContext().getText(R.string.please_ic_swiper_2).toString();
            bounds = new Rect();
            mPaint.getTextBounds(icText, 0, icText.length(), bounds);
            canvas.drawText(
                    icText,
                    (ZZTongActivity.screenWidth - bounds.width()) / 2,
                    topText,
                    mPaint);
            // 休眠以控制最大帧频为每秒约30帧
            if (rotate > ZZTongActivity.screenWidth * 0.8) {
                Thread.sleep(200);
                isBack = true;
            }
            // canvas.drawBitmap(titleImage,
            // (Main.screenWidth - titleImage.getWidth()) / 2,
            // topPosition, mPaint);
            // if(phoneImage ==null || phoneImage.isRecycled())
            // return;
            // canvas.drawBitmap(
            // phoneImage,
            // (Main.screenWidth - phoneImage.getWidth()) / 2,
            // topPosition + titleImage.getHeight()
            // + spacePostion + cardImage.getHeight()/2,
            // mPaint);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (canvas != null) {
                    // HPLog.e("time", "unlockCanvas");
                    surfaceHolder.unlockCanvasAndPost(canvas);// 解锁画布，提交画好的图像
                }
            } catch (Exception e) {
            }
        }
    }

    private void update() {
        Canvas canvas = null;
        try {
            canvas = surfaceHolder.lockCanvas(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (canvas != null) {
            paint(canvas);
        } else {
            // 避免多次进入导致黑屏的问题。具体原因请看SurfaceView源码 BUG 6890
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP) {
            if (backLeftMin < event.getX() && event.getX() < backLeftMax && event.getY() < backHeightMax) {
                HPLog.i("Test", "返回按钮-----");
                if (backListener != null) {
                    backListener.back();
                }
            }
        }
        return true;
    }

    public void setBackListener(SwiperCardKLFActivity.BackListener backListener) {
        this.backListener = backListener;
    }
}
